
<style lang="scss" scoped>
.file-list {
    .file-item {
        padding: 5px;
        margin: 5px 0;
        transition: all ease 200ms;
        &:hover {
            background-color: #ebebeb;
        }

        .file-info {
            display: flex;
            justify-content: space-between;

            .file-operate-item {
                margin: 0 5px;
                cursor: pointer;
                transition: color ease 400ms;
                &:hover {
                    color: rgb(141, 141, 141);
                }
            }
        }
    }
}
</style>
<template>
    <div class="clearfix">
        <!-- 简易模式 -->
        <div v-if="type === 0">
            <Upload
                :show-upload-list="false"
                type="click"
                :action="action"
                :accept="accept"
                :multiple="multiple"
                :before-upload="handleUploadFile"
            >
                <Button v-bind="easyMode">{{easyMode.text}}</Button>
            </Upload>
        </div>
        <!-- modal模式 -->
        <div v-else>
            <Upload
                ref="refmutiupload"
                :show-upload-list="false"
                type="drag"
                :action="action"
                :accept="accept"
                :multiple="multiple"
                :before-upload="handleUploadFile"
            >
                <div style="padding: 20px 0">
                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                    <p>{{$t('global.common.select_attachment', { defaultValue: '请选择文件' })}}</p>
                </div>
            </Upload>
            <slot name="content"></slot>
            <ul class="file-list">
                <li class="file-item" v-for="(item, index) in fileList" :key="item.key">
                    <div class="file-info">
                        <div class="file-name">
                            <Icon type="ios-document" />
                            {{item.name}}
                        </div>
                        <div class="file-operate">
                            <Icon
                                v-if="item.status !== 1"
                                class="file-operate-item"
                                :size="20"
                                type="ios-trash"
                                @click="deleteOne(index)"
                            />
                            <!-- <Icon v-if="item.status === 0" class="file-operate-item" :size="20" type="ios-play" @click="uploadOne(index)" /> -->
                            <!-- <Icon v-else class="file-operate-item" :size="20" type="ios-pause" @click="stopOne(index)" /> -->
                        </div>
                    </div>
                    <Progress :stroke-width="6" :percent="item.percent" :status="item.uploadStatus == 1 ? 'active' : 'wrong'"></Progress>
                </li>
            </ul>
            <div class="margin-top-10 margin-bottom-10 color-error">
                <div v-if="warningtitle" v-html="warningtitle"></div>
            </div>
            <div class="pull-right margin-top-10">
                <slot name="footer"></slot>
                <div class="text-right">
                    <Button
                        v-if="download"
                        type="info"
                        class="margin-right-15"
                        @click.stop="download"
                        icon="md-cloud-download"
                    >{{$t('global.common.download_template', { defaultValue: '下载模板' })}}</Button>
                    <Button
                        v-if="!hasFinish"
                        class="margin-right-15"
                        type="success"
                        @click.stop="upload"
                        icon="ios-cloud-upload-outline"
                    >{{$t('global.common.upload', { defaultValue: '上传' })}}</Button>
                    <Button v-else class="margin-right-15" type="primary" @click="finishUpload">{{$t('global.datepicker.confirm', { defaultValue: '确认' })}}</Button>
                    <Button @click="handleClose">{{$t('global.common.close', { defaultValue: '关闭' })}}</Button>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import HttpService from "../../service/baseHttp";
import { HttpDelFile } from "../../service/base";
export default {
    props: [
        "action", 
        "accept", 
        "data", 
        "name", 
        "multiple", 
        "type", 
        "easyMode", 
        "validFile", 
        "beforeUpload", 
        "formatter", 
        "download",
        'warningtitle',
        "autoHandle"
    ],
    data() {
        return {
            fileList: [],
            configData: {
                ...this.propsData,
            },
            status: [
                {
                    value: 0,
                    label: "待上传",
                },
                {
                    value: 1,
                    label: "上传中",
                },
                {
                    value: 2,
                    label: "已上传",
                },
                {
                    value: 3,
                    label: "上传失败"
                }
            ],
            result: {
                items: [],
                opAt: "",
                organizationId: global.SYSID,
                originData: [],
            },
            hasFinish: false,
        };
    },
    methods: {
        handleUploadFile(file) {
            let flag = true;
            console.log(this);
            if (this.validFile) {
               flag = this.validFile(file);
            }
            if (!flag) return false;
            let fileItem = {
                id: 0,
                name: file.name,
                file: file,
                percent: 0,
                status: 0,
                uploadStatus: 1
            }
            this.fileList.push(fileItem);
            // 简易模式
            if (this.type === 0) {
                this.fileList = [fileItem]
                this.uploadOne(0)
            }
            return false;
        },
        async upload() {
            // 如果上传列表为空，则不执行任何操作
            if (!this.fileList || !this.fileList.length) return
            // 提交前验证
            if (this.beforeUpload && ! await this.beforeUpload(this.fileList)) return
            let promiseArr = this.fileList.map((item, index) => {
                item.uploadStatus = 1;
                item.percent = 0;
                return this.ajaxFile(index).then((res) => {
                    item.percent = 100;
                    // 是否需要自动处理多条（绝大多数情况不需要）
                    if (this.autoHandle) {
                        if (this.formatter) {
                            this.result = this.formatter(res, item)
                        }
                        else {
                            item.status = 2;
                            item.id = res.data.entity.id || null;
                            item.result = res.data;
                            this.result.opAt = item.result.entity.createdAt || null;
                            this.result.items.push({
                                attachId: item.result.entity.id || null,
                                attachOpAt: item.result.entity.createdAt || null,
                                attachTitle: item.result.entity.title || null,
                                attachBrief: item.result.entity.brief || null,
                                attachUrl: item.result.genUrl || null,
                                createdName:item.result.entity.createdName || null,
                                createdBy:item.result.entity.createdBy || null,
                                // filename: item.result.entity.filename
                            });
                            item.uploadStatus = 1;
                            this.result.originData.push(item.result);
                        }
                    }
                    else {
                        this.$Message.success(res.message);
                        this.$emit("on-success", res);
                        setTimeout(() => {
                            this.$emit('on-update');
                        }, 200);
                    }
                }, err => {
                    item.uploadStatus = 0;
                    // 上传失败更改文件状态
                    item.status = 3;
                    throw err;
                });
            });
            Promise.all(promiseArr).then(() => {
                this.$emit("on-success", this.result);
                // 简易模式清空数据
                if (this.type === 0) {
                    this.reset()
                }
            }, err => {
                this.$Message.error({
                    content: err.message,
                    duration: 30,
                    closable: true
                });
            });
        },
        ajaxFile(index) {
            let url = this.action
                ? this.action
                : process.env.VUE_APP_APIURL_UC +
                  "/api/v1/BizAttach/uploadFile";
            // 用原来的构造数据方式
            let formData = new FormData();
            Object.entries(this.data || {}).forEach(([key, val]) => {
                formData.append(key, val);
            });
            formData.append(this.name, this.fileList[index].file);
            formData.append("contextId", global.SYSID);
            let that = this;
            const args = [
                url,
                formData,
                {
                    headers: {
                        "Content-Type": "multipart/form-data",
                        Authorization: "Bearer " + global.AUTH_TOKEN,
                    },
                    withCredentials: true,
                    transformRequest(data) {
                        return data;
                    },
                    // 监听上传进度
                    onUploadProgress: function (progressEvent) {
                        that.fileList[index].status = 1;
                        that.fileList[index].percent =
                            (progressEvent.loaded / progressEvent.total) * 99;
                    },
                    // cancelToken: cancelXHR.token
                },
            ];
            // 发起请求
            const ajaxRequest =
                !this.action && typeof this.ajaxRequest === "function"
                    ? this.ajaxRequest(...args.slice(1))
                    : HttpService.post(...args);
            return ajaxRequest;
        },
        // 简易模式直接返回接口数据
        uploadOne(index) {
            this.ajaxFile(index).then(
                (res) => {
                    this.$Message.success(res.message);
                    this.$emit("on-success", res);
                },
                (err) => {
                    this.$Message.error({
                        content: err.message,
                        duration: 30,
                        closable: true
                    });
                }
            );
        },
        async deleteOne(index) {
            // 未上传和上传失败直接删除
            if ([0, 3].includes(this.fileList[index].status)) {
                this.fileList.splice(index, 1);
            }
            // 已上传调用接口删除
            else {
                await HttpDelFile({
                    id: this.fileList[index].id,
                }).then(
                    (res) => {
                        this.fileList.splice(index, 1);
                    },
                    (err) => {
                        this.$Message.error({
                            content: err.message,
                            duration: 30,
                            closable: true
                        });
                    }
                );
            }
        },
        reset () {
            this.fileList = []
            this.result = {
                items: [],
                opAt: "",
                organizationId: global.SYSID,
                originData: [],
            };
        },
        clearUpload () {
            this.$set(this, 'fileList', []);
        },
        handleClose () {
            // this.$emit('on-cancel');
            this.$emit("on-close");
        }
    },
};
</script>